package com.wgts.wgts.mvp.view.activity.myorder;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.wgts.wgts.R;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.dialog.WonderLoadingDialog;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerMyOrderFragmentComponent;
import com.wgts.wgts.dagger.module.MyOrderFragmentModule;
import com.wgts.wgts.localbean.GoodsData;
import com.wgts.wgts.localbean.PayData;
import com.wgts.wgts.mvp.presenter.IMyOrderFragmentPersenter;
import com.wgts.wgts.mvp.view.IMyOrderFragmentView;
import com.wgts.wgts.mvp.view.activity.pay.ContinuePayActivity;
import com.wgts.wgts.netmodle.resp.MyOrderListEntity;
import com.wgts.wgts.thirdParty.pay.PayTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/*
 *
 *
 *   data:2018/9/1010:38
 *
 */public class MyOrderFragment extends LazyBaseFragment implements IMyOrderFragmentView {
    @BindView(R.id.My_order_fragment_recycle)
    RecyclerView MyOrderFragmentRecycle;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.none_data_ly)
    LinearLayout noneDataLy;
    @BindView(R.id.net_error_ly)
    LinearLayout netErrorLy;
    private Integer type;

    private MyOrderAdapter adapter;

    private String orderState;

    private PayData payData;

    private List<MyOrderListEntity> entityList;

    private WonderLoadingDialog dialog;

    //判断刷新
    private boolean isCreated = false;


    @Inject
    IMyOrderFragmentPersenter persenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type");
        }
        View view = inflater.inflate(R.layout.my_order_fragment, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void init() {
        DaggerMyOrderFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .myOrderFragmentModule(new MyOrderFragmentModule(this))
                .build()
                .inject(this);
        entityList = new ArrayList<>();
    }

    private void initView() {
        dialog = new WonderLoadingDialog(getActivity());
        refreshLayout.setEnableRefresh(true);//启用刷新
        refreshLayout.setEnableHeaderTranslationContent(true);
        MyOrderFragmentRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new MyOrderAdapter(getActivity(), entityList, getActivity().getSupportFragmentManager(), persenter);
        MyOrderFragmentRecycle.setAdapter(adapter);
        adapter.setOnItemClickListen(new MyOrderAdapter.onItemClickListen() {
            @Override
            public void onClick(String orderId, String payStatus) {
                Intent intent = new Intent(getActivity(), MyOrderDetailsActivity.class);
                intent.putExtra(MyOrderDetailsActivity.ORDER_ID, orderId);
                intent.putExtra(MyOrderDetailsActivity.PAY_STATUS, payStatus);
                startActivityForResult(intent, ContinuePayActivity.PAY_RESULT_OK);
            }
        });
        refresh();
        loadMore();
    }

    @Override
    protected void loadData() {
        getOrderStatus(type);
        initView();
        if (dialog != null){
            dialog.show();
        }
        persenter.initList(orderState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static Fragment getMyOrderFragment(Integer position) {
        Fragment fragment = new MyOrderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", position);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void myOrderList(List<MyOrderListEntity> entity, boolean noMore) {
        if(dialog!=null){
            if(dialog.isShowing()){
                dialog.dismiss();
            }
        }
        if (entity.size() > 0){
            noneDataLy.setVisibility(View.GONE);
            netErrorLy.setVisibility(View.GONE);
        }else {
            noneDataLy.setVisibility(View.VISIBLE);
            netErrorLy.setVisibility(View.GONE);
        }
        isCreated = true;
        refreshLayout.finishRefresh();
        entityList.clear();
        entityList.addAll(entity);
        adapter.setNoMore(noMore);
        adapter.notifyDataSetChanged();

        if (noMore) {
            refreshLayout.setEnableLoadmore(false);
        } else {
            refreshLayout.setEnableLoadmore(true);
        }
    }

    @Override
    public void againOrderList() {
        persenter.initList(orderState);
    }

    @Override
    public void loadMore(List<MyOrderListEntity> entity, boolean noMore) {
        refreshLayout.finishLoadmore();
        entityList.addAll(entity);
        adapter.setNoMore(noMore);
        adapter.notifyDataSetChanged();
        if (noMore) {
            refreshLayout.setEnableLoadmore(false);
        } else {
            refreshLayout.setEnableLoadmore(true);
        }
    }

    @Override
    public void goPay(String orderId, String needPayPrice, String orderType, String commissionProfit, String orderCode) {
        payData = new PayData();
        Intent intent = new Intent(getActivity(), ContinuePayActivity.class);
        payData.orderId = orderId;
        payData.needPayPrice = needPayPrice;
        payData.orderType = orderType;
        payData.commissionProfit = commissionProfit;
        payData.orderCode = orderCode;
        intent.putExtra(PayTools.PAY_DATE, payData);
        startActivityForResult(intent, ContinuePayActivity.PAY_RESULT_OK);
    }

    @Override
    public void goEvaluate(String orderId) {
        Intent intent = new Intent(getActivity(), EvaluateActivity.class);
        intent.putExtra(EvaluateActivity.ORDER_ID, orderId);
        startActivityForResult(intent, ContinuePayActivity.PAY_RESULT_OK);
    }

    @Override
    public void applyForAfterSell(String orderId, String orderCode, GoodsData data) {
        Intent intent = new Intent(getActivity(), AfterSaleActivity.class);
        intent.putExtra(AfterSaleActivity.ORDER_ID, orderId);
        intent.putExtra(AfterSaleActivity.ORDER_CODE, orderCode);
        intent.putExtra(AfterSaleActivity.GOODS_DATE, data);
        startActivityForResult(intent, ContinuePayActivity.PAY_RESULT_OK);
    }

    @Override
    public void onError(int status, String msg) {
        if(dialog!=null){
            if(dialog.isShowing()){
                dialog.dismiss();
            }
        }
        if (noneDataLy != null && netErrorLy != null){
            noneDataLy.setVisibility(View.GONE);
            netErrorLy.setVisibility(View.VISIBLE);
            isCreated = true;
            MoHuToast.showToast(msg);
        }
    }

    //获取订单状态
    private void getOrderStatus(Integer orderType) {
        switch (orderType) {
            case 0:
                orderState = "";
                break;
            case 1:
                orderState = "UNPAID";
                break;
            case 2:
                orderState = "UNRECEIPT";
                break;
            case 3:
                orderState = "RETURN_GOOD";
                break;

        }
    }

    private void refresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                persenter.initList(orderState);
            }
        });
    }

    private void loadMore() {
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                persenter.addMore(orderState);
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            if (isCreated) {
                loadData();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ContinuePayActivity.PAY_RESULT_OK && data != null) {
            persenter.initList(orderState);
        }
    }

    @OnClick(R.id.net_error_ly)
    public void onViewClicked() {
        if (dialog != null){
            dialog.show();
        }
        persenter.initList(orderState);
    }
}
